package cn.rxmind.dlicense.core.validator;

import cn.rxmind.dlicense.core.base.DLicenseContent;

import java.util.*;
import java.util.function.Consumer;

/**
 * 封装校验器集合
 *
 * @author renxin
 * @email renxinzhiliangzhi@163.com
 * @date 2021/4/14 2:14 下午
 */
public class DLicenseValidatorList<T extends DLicenseValidator> {

    private final List<T> validators;

    private final Set<Class<? extends DLicenseValidator>> validatorTypes;

    public DLicenseValidatorList() {
        this.validatorTypes = new HashSet<>();
        this.validators = new ArrayList<>();
    }

    @SafeVarargs
    public final void addValidators(T... validators){

        Arrays.stream(validators)
                .filter(validator -> !this.validatorTypes.contains(validator.getClass()))
                .forEach(validator ->{
                    this.validators.add(validator);
                    this.validatorTypes.add(validator.getClass());
                });
        this.validators.sort(Comparator.comparingInt(DLicenseValidator::order));
    }

    /**
     * 按顺序执行校验
     *
     * @param content
     */
    public void validateByOrder(final DLicenseContent content) {

         validators.forEach(utryLicenseValidator -> utryLicenseValidator.validateLicense(content));
    }

    /**
     * 遍历逻辑
     *
     * @param action
     */
    public void forEach(Consumer<T> action){
        this.validators.forEach(action);
    }
}
